/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package descriptor;

import database.DatabaseObject;
import database.DatabaseObjectFactory;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import runtime.RuntimeInstanceFactory;

/**
 *
 * @author Alejandro
 */
public class SqlParser implements Initializer {
    private ResultSet rs;

    public SqlParser(ResultSet rs) {
        this.rs = rs;
    }

    @Override
    public Object init(Object obj) {
        String tableName = (String) obj;
        Collection<Property> properties = new LinkedList<Property>();
        Application app = Application.getInstance();
        Template template = app.getTemplate(tableName);
        Iterable<PropertyTemplate> propertyTemplates = template.getPropertyTemplateCollection();
        RuntimeInstanceFactory factory = new DatabaseObjectFactory();
        for(PropertyTemplate pt: propertyTemplates) {
            try {
                DatabaseObject value = (DatabaseObject) factory.getObject(pt.getTypeName());
                if (rs.getString(pt.getName()) != null)
                    value.setValue(rs.getString(pt.getName()));
                else {
                    if (!pt.isNotNull()) {
                        value.setValue(pt.getNullReplacingValue());
                    }
                }
                properties.add(new Property(pt.getName(), value));
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }
        return properties;
    }

    @Override
    public void setManagedObject(ManagedObject obj) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}
